import json
import os
import sys
import time
import tkinter
import tkinter.messagebox as messagebox
import urllib.request
import uuid

import psutil
import qrcode

path = 'url'
if os.path.exists(path):
    os.remove(path)

name = "suoniu"


def proc_exist(process_name):
    pl = psutil.pids()
    num = 0
    for pid in pl:
        if psutil.Process(pid).name() == process_name:
            num += 1
            if num > 2:
                return pid


if isinstance(proc_exist(name + '.exe'), int):
    sys.exit()

root = tkinter.Tk()
root.title('索牛云播')  # 窗口标题
root.iconbitmap('logo.ico')
root.resizable(False, False)  # 固定窗口大小
windowWidth = 400  # 获得当前窗口宽
windowHeight = 400  # 获得当前窗口高
screenWidth, screenHeight = root.maxsize()  # 获得屏幕宽和高
geometryParam = '%dx%d+%d+%d' % (
    windowWidth, windowHeight, (screenWidth - windowWidth) / 2, (screenHeight - windowHeight) / 2)
print(geometryParam)
root.geometry(geometryParam)  # 设置窗口大小及偏移坐标
root.update()
root.wm_attributes('-topmost', 1)  # 窗口置顶

uuid = uuid.uuid5(uuid.NAMESPACE_DNS, name + str(time.time()))
print(uuid)

qr = qrcode.QRCode(
    version=5,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=8,
    border=2,
)

qr.add_data(uuid)

qr.make(fit=True)
img = qr.make_image()
filename = 'qrcode.gif'
img.save(filename)

label_text = tkinter.Label(root, text='  ', font='宋体 -8')
label_text.pack()
img_gif = tkinter.PhotoImage(file='qrcode.gif')
label_img = tkinter.Label(root, image=img_gif)
label_img.pack()
label_text = tkinter.Label(root, text='  ', font='宋体 -8')
label_text.pack()
label_text = tkinter.Label(root, text='请打开索牛云播手机版扫码开始直播', font='宋体 -16')
label_text.pack()


def clock():
    print(time.time())
    response = urllib.request.urlopen("https://apidev.suoniu.cn/live/pushLive?uniqueCode=" + str(uuid))
    decode = response.read().decode('utf-8')
    print(decode)
    res = json.loads(decode)
    print(res)
    if res['code'] == 1000:
        url_ = res['data']['pushUrl']
        print(url_)
        with open('url', 'w') as f:
            f.write(url_)
        root.destroy()
    else:
        root.after(1000, clock)


clock()


def on_closing():
    if messagebox.askokcancel("索牛云播", "确定不扫码开始直播?"):
        with open('exit', 'w') as f:
            f.write(name)
        root.destroy()


root.protocol("WM_DELETE_WINDOW", on_closing)
root.mainloop()
